using Newtonsoft.Json;
using Process.Domain.DTO.InputDTO;
using Process.Domain.DTO.OutDTO;
using Process.Domain.Entities;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.Json;
using System.Threading.Tasks;
using WorkflowCore.Interface;

namespace Process.Application.Services
{
    /// <summary>
    /// 工艺流程排序工具类
    /// </summary>
    public class ProcessFlowSorter
    {
        private readonly IWorkflowHost _workflowHost;
        private readonly IDefinitionLoader _definitionLoader;
        private readonly IWorkflowRegistry _workflowRegistry;
        public ProcessFlowSorter(IWorkflowHost workflowHost,IDefinitionLoader definitionLoader,IWorkflowRegistry workflowRegistry)
        {
            _workflowHost = workflowHost;
            _definitionLoader = definitionLoader;
            _workflowRegistry = workflowRegistry;
        }
        public static List<StepNode> SortWorkflow(WorkflowSortInput workflow)
        {
            if (workflow == null || workflow.nodes == null || workflow.connections == null)
            {
                throw new ArgumentNullException("工艺流程数据不完整");
            }

            // 构建图结构（邻接表）
            Dictionary<string, List<string>> graph = new Dictionary<string, List<string>>();
            foreach (var node in workflow.nodes)
            {
                graph[node.id] = new List<string>();
            }

            foreach (var connection in workflow.connections)
            {
                if (graph.ContainsKey(connection.source))
                {
                    graph[connection.source].Add(connection.target);
                }
            }

            // 使用BFS进行拓扑排序
            List<WorkflowNode> sortedNodes = new List<WorkflowNode>();
            HashSet<string> visited = new HashSet<string>();
            Queue<string> queue = new Queue<string>();

            // 查找开始节点（类型为start的节点）
            var startNode = workflow.nodes.FirstOrDefault(n => n.type.ToLower() == "start");
            if (startNode == null)
            {
                throw new InvalidOperationException("找不到开始节点");
            }

            // 从开始节点开始排序
            queue.Enqueue(startNode.id);
            visited.Add(startNode.id);

            while (queue.Count > 0)
            {
                string currentId = queue.Dequeue();

                // 添加当前节点到结果列表
                var currentNode = workflow.nodes.FirstOrDefault(n => n.id == currentId);
                if (currentNode != null)
                {
                    sortedNodes.Add(currentNode);
                }

                // 遍历所有连接的节点
                if (graph.ContainsKey(currentId))
                {
                    foreach (var nextId in graph[currentId])
                    {
                        if (!visited.Contains(nextId))
                        {
                            visited.Add(nextId);
                            queue.Enqueue(nextId);
                        }
                    }
                }
            }

            // 检查是否所有节点都已访问
            if (visited.Count != workflow.nodes.Count())
            {
                // 有些节点未被访问到，可能是工艺流程中存在孤立节点或循环
                var unvisitedNodes = workflow.nodes.Where(n => !visited.Contains(n.id)).ToList();
                foreach (var node in unvisitedNodes)
                {
                    sortedNodes.Add(node); // 将未访问的节点添加到最后
                }
            }

            // 将排序后的节点转换为StepNode格式
            List<StepNode> stepNodes = new List<StepNode>();

            // 创建节点映射，用于设置StepNextId
            Dictionary<string, string> nodeIdToStepIdMap = new Dictionary<string, string>();
            foreach (var node in sortedNodes)
            {
                // 使用processId作为StepId，如果为空则使用节点Id
                string stepId = !string.IsNullOrEmpty(node.processId) ? node.processId : node.id;
                nodeIdToStepIdMap[node.id] = stepId;
            }

            // 查找End节点
            var endNode = workflow.nodes.FirstOrDefault(n => n.type.ToLower() == "end");
            string endNodeId = endNode?.id;
            string endNodeStepId = endNode != null ? nodeIdToStepIdMap[endNode.id] : "end";
            
            // 标记哪些节点直接连接到End节点
            HashSet<string> nodesConnectingToEnd = new HashSet<string>();
            
            if (endNode != null)
            {
                foreach (var conn in workflow.connections)
                {
                    if (conn.target == endNodeId)
                    {
                        nodesConnectingToEnd.Add(conn.source);
                    }
                }
            }

            // 创建StepNode列表
            for (int i = 0; i < sortedNodes.Count; i++)
            {
                var currentNode = sortedNodes[i];

                // 获取当前节点的StepId
                string stepId = nodeIdToStepIdMap[currentNode.id];

                // 确定下一个节点的StepId
                string nextStepId = "";
                
                // 不是最后一个节点且不是end类型
                if (i < sortedNodes.Count - 1 && currentNode.type.ToLower() != "end")
                {
                    // 如果当前节点连接到End节点，则StepNextId为"end"
                    if (nodesConnectingToEnd.Contains(currentNode.id))
                    {
                        nextStepId = "end";
                    }
                    else
                    {
                        // 获取图中的下一个节点
                        var connections = graph[currentNode.id];
                        if (connections.Count > 0)
                        {
                            string nextNodeId = connections[0];
                            nextStepId = nodeIdToStepIdMap[nextNodeId];
                        }
                    }
                }

                // 解析审核人ID
                long auditUserId = 0;
                if (!string.IsNullOrEmpty(currentNode.approver))
                {
                    long.TryParse(currentNode.approver, out auditUserId);
                }

                // 创建StepNode
                var stepNode = new StepNode
                {
                    StepId = stepId,
                    StepName = currentNode.name,
                    StepNextId = nextStepId,
                    AuditUserId = auditUserId,
                    AuditUserName = currentNode.approverName ?? ""
                };

                stepNodes.Add(stepNode);
            }

            return stepNodes;
        }

        /// <summary>
        /// 表示流程中的一个步骤节点。
        /// </summary>
     

        ///// <summary>
        ///// 测试方法：对示例JSON进行排序
        ///// </summary>
        ///// <param name="jsonStr">工艺流程JSON字符串</param>
        ///// <returns>排序后的工艺流程</returns>
        //public static SortedWorkflowDTO TestSort(string jsonStr)
        //{
        //    try
        //    {
        //        var options = new JsonSerializerOptions
        //        {
        //            PropertyNameCaseInsensitive = true,
        //            PropertyNamingPolicy = JsonNamingPolicy.CamelCase
        //        };
                
        //        var workflow = System.Text.Json.JsonSerializer.Deserialize<WorkflowSortInput>(jsonStr, options);
                
        //        if (workflow == null)
        //        {
        //            throw new ArgumentNullException("无法将JSON转换为工艺流程对象");
        //        }
                
        //       return SortWorkflow(workflow);
        //    }
        //    catch (Exception ex)
        //    {
        //        Console.WriteLine($"排序发生错误: {ex.Message}");
        //        throw;
        //    }
        //}
        
        ///// <summary>
        ///// 测试方法：输出排序结果
        ///// </summary>
        //public static string TestSortWithSampleJson()
        //{
        //    string sampleJson = @"{""id"":""workflow-1751462489694"",""name"":""新工艺流程"",""description"":"""",""nodes"":[{""id"":""start"",""type"":""start"",""name"":""开始"",""position"":{""x"":100,""y"":100}},{""id"":""end"",""type"":""end"",""name"":""结束"",""position"":{""x"":761.9333190917969,""y"":426.7333221435547}},{""id"":""node-1751462491158"",""processId"":""9fbf9c19-5464-42bf-816e-30ece1f34ee4"",""type"":""process"",""name"":""切割工序"",""position"":{""x"":381.9333190917969,""y"":204.7333221435547},""department"":""8362372513"",""departmentName"":""人员部门"",""approver"":""1938574780504478150"",""approverName"":""束童""}],""connections"":[{""id"":""conn-1751462557119"",""source"":""start"",""target"":""node-1751462491158"",""type"":""normal""},{""id"":""conn-1751462560287"",""source"":""node-1751462491158"",""target"":""end"",""type"":""normal""}]}";
            
        //    try
        //    {
        //        var result = TestSort(sampleJson);
        //        return System.Text.Json.JsonSerializer.Serialize(result, new JsonSerializerOptions { WriteIndented = true });
        //    }
        //    catch (Exception ex)
        //    {
        //        return $"排序测试失败: {ex.Message}";
        //    }
        //}


        public static void WorkflowDefition(string serializedWorkflow)
        { 
            var step=JsonConvert.DeserializeObject<List<WorkflowNodeDTO>>(serializedWorkflow, new JsonSerializerSettings 
            { 
                StringEscapeHandling = StringEscapeHandling.Default
            });

        }
       
    }
} 